﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.Serialization;
using System.Data;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;

namespace WebApplication1
{
    public partial class SearchResult : System.Web.UI.Page
    {
        private void BindData(int iTagId)
        {
            PagedDataSource pds = new PagedDataSource();

            DataView dataView = getDataSource(iTagId).DefaultView;
            string order = string.Empty;
            if (ViewState["Field"] != null)
            {
                order = ViewState[ViewState["Field"].ToString()].ToString();
                if (!string.IsNullOrEmpty(order))
                    dataView.Sort = ViewState["Field"] + " " + order;
            }

            DataTable dt = getDataSource(iTagId);
            List<Location> m_list = new List<Location>();
            
            for (int ix = 0; ix < dt.Rows.Count; ix++)
            {
                Location new_Location = new Location();
                new_Location.Name = dt.Rows[ix]["Name"].ToString();
                new_Location.Description = dt.Rows[ix]["BriefInfo"].ToString();
                new_Location.Longitude = (double)dt.Rows[ix]["Longitude"];
                new_Location.Latitude = (double)dt.Rows[ix]["Latitude"];

                m_list.Add(new_Location);
            }

            HiddenField1.Value = ToJsJson(m_list);


            pds.DataSource = dataView;
            //pds.AllowCustomPaging = true;
            pds.AllowPaging = true;
            //pds.AllowServerPaging = true;
            pds.PageSize = 15;


            int CurPage;
            if (Request.QueryString["Page"] != null)
                CurPage = Convert.ToInt32(Request.QueryString["Page"]);
            else
                CurPage = 1;
            int TotalCount = 0;//总记录数
            int TotalPage = 1; //总页数


            TotalCount = getDataSource(iTagId).DefaultView.Count;

            if (TotalCount == 0)
                TotalPage = 1;
            else
            {
                if (TotalCount % pds.PageSize == 0)
                    TotalPage = TotalCount / pds.PageSize;
                else
                    TotalPage = TotalCount / pds.PageSize + 1;
            }

            pds.CurrentPageIndex = CurPage - 1;
            lblCurrentPage.Text = "共" + TotalCount.ToString() + "条记录 当前页：" + CurPage.ToString() + "/" + TotalPage;

            lnkFrist.NavigateUrl = Request.CurrentExecutionFilePath + path+"&Page=1";
            if (!pds.IsFirstPage)
                lnkPrev.NavigateUrl = Request.CurrentExecutionFilePath +path+ "&Page=" + Convert.ToString(CurPage - 1);

            if (!pds.IsLastPage)
                lnkNext.NavigateUrl = Request.CurrentExecutionFilePath+path + "&Page=" + Convert.ToString(CurPage + 1);
            lnkEnd.NavigateUrl = Request.CurrentExecutionFilePath +path+ "&Page=" + TotalPage;


            rptOrgnization.DataSource = pds;
            rptOrgnization.DataBind();

        }

        private string path = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {

            if (Request.QueryString["Lo"] == null || Request.QueryString["La"] == null)
            {
                Response.Redirect("~/Search.aspx");
            }

            path = "?Lo=" + Request.QueryString["Lo"] + "&" + "La=" + Request.QueryString["La"];
            

            if (!IsPostBack)
            {
                tbxSearch.Attributes.Add("onclick", "this.value=''");
                BindData(-1);
                DataTable dt = new DataTable();
                SQLHelper.getRootTags(out dt);

                rptMenu1.DataSource = dt;
                rptMenu1.DataBind();
            }

        }

        protected void AddFavourite_Command(object sender, CommandEventArgs e)
        {
            if (Session["UserInfo"] == null)
            {
                Response.Write("<script>alert('请先登录!');location.href='Login.aspx';</script>");
                return;
            }
            int iresult = SQLHelper.AddFavouriteSchoolToAccountId(((Entity.UserInfo)Session["UserInfo"]).UserId, Convert.ToInt32(e.CommandArgument));
            if (iresult != 1)
                Response.Write("<script>alert('收藏失败!');location.href='Home.aspx';</script>");
            else
                Response.Write("<script>alert('收藏成功!');location.href='PersonCenter.aspx';</script>");
        }


        public static string ToJsJson(object item)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(item.GetType());
            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, item);
                StringBuilder sb = new StringBuilder();
                sb.Append(Encoding.UTF8.GetString(ms.ToArray()));
                return sb.ToString();
            }
        }

        //反序列化

        public static T FromJsonTo<T>(string jsonString)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
            {
                T jsonObject = (T)ser.ReadObject(ms);
                return jsonObject;
            }
        }
        private DataTable getDataSource(int iTagId)
        {
            DataTable dt = new DataTable();
            if (iTagId == -1)
            {
                
                if (Request.QueryString["TagId"] == null||Request.QueryString["TagId"]=="A")
                    SQLHelper.SearchSchool(new Entity.MapPoint(float.Parse(Request.QueryString["Lo"]), float.Parse(Request.QueryString["La"])), out dt);
                else
                {
                    SQLHelper.SearchSchoolByTag(new Entity.MapPoint(float.Parse(Request.QueryString["Lo"]), float.Parse(Request.QueryString["La"])), Convert.ToInt32(Request.QueryString["TagId"]), out dt);
                }
                
            }
            else
            {
                SQLHelper.SearchSchoolByTag(new Entity.MapPoint(float.Parse(Request.QueryString["Lo"]), float.Parse(Request.QueryString["La"])), iTagId, out dt);
            }
            return dt;
        }
      
        
        protected void lbTag1Click(object sender, CommandEventArgs e)
        {
            //根据e.CommandArgument判断,它可以绑定是哪行要删除
            //
            int i = Convert.ToInt32(e.CommandArgument);
            DataTable dt = new DataTable();
            SQLHelper.getChildTagsByParentId(i, out dt);
            rptMenu2.DataSource = dt;
            rptMenu2.DataBind();
            rptMenu3.DataSource = null;
            rptMenu3.DataBind();
            BindData(i);
            secondDiv.Attributes.CssStyle["display"] = "block";

        }
        protected void lbTag2Click(object sender, CommandEventArgs e)
        {
            int i = Convert.ToInt32(e.CommandArgument);
            DataTable dt = new DataTable();
            SQLHelper.getChildTagsByParentId(i, out dt);
            rptMenu3.DataSource = dt;
            rptMenu3.DataBind();
            BindData(i);
            thirdDiv.Attributes.CssStyle["display"] = "block";
        }
        protected void lbTag3Click(object sender, CommandEventArgs e)
        {
            int i = Convert.ToInt32(e.CommandArgument);
            BindData(i);
        }

        /// <summary>
        /// tagID
        /// </summary>
        private int i = -1;


        protected void rptOrgnization_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            //判断里层repeater处于外层repeater的哪个位置（ AlternatingItemTemplate，FooterTemplate，

            //HeaderTemplate，，ItemTemplate，SeparatorTemplate）
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Repeater rep = e.Item.FindControl("subrptTag") as Repeater;//找到里层的repeater对象
                DataRowView rowv = (DataRowView)e.Item.DataItem;//找到分类Repeater关联的数据项 
                string text = rowv["Id"].ToString(); //获取填充子类的id 
                DataTable dt = new DataTable();
                SQLHelper.getTagsBySchoolId(Convert.ToInt32(text), out dt);
                rep.DataSource = dt;
                rep.DataBind();
            }

        }

        protected void DistanceLinkBtn_Click(object sender, EventArgs e)
        {
            if (ViewState["Distance"] == null)
            {
                ViewState["Distance"] = "ASC";            
            }
            else
            {
                if (ViewState["Distance"].ToString().Trim() == "ASC")
                {
                    ViewState["Distance"] = "DESC";         
                }
                else
                {
                    ViewState["Distance"] = "ASC";
                }
            }
            ViewState["Field"] = "Distance";
            BindData(i);
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Person _Person = new Person();
            _Person.Name = "江湖小子3";
            _Person.Address = "北京4";
            _Person.Tel = "010-10000000";

            Person _Person1 = new Person();
            _Person1.Name = "江湖小4子";
            _Person1.Address = "北京4";
            _Person1.Tel = "010-100000300";

            List<Person> persons = new List<Person>();
            persons.Add(_Person);
            persons.Add(_Person1);
            string test = ToJsJson(persons);
            HiddenField1.Value = test;
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Search.aspx?text=" + Server.UrlEncode(tbxSearch.Text));
        }

        protected void PopularityLinkBtn_Click(object sender, EventArgs e)
        {
            if (ViewState["Popularity"] == null)
            {
                ViewState["Popularity"] = "DESC";
            }
            else
            {
                if (ViewState["Popularity"].ToString().Trim() == "ASC")
                {
                    ViewState["Popularity"] = "DESC";
                 
                }
                else
                {
                    ViewState["Popularity"] = "ASC";
                   
                }
            }
            ViewState["Field"] = "Popularity";
            BindData(i);
        }

        protected void StarLevelLinkBtn_Click(object sender, EventArgs e)
        {
            if (ViewState["SL_Integrate"] == null)
            {
                ViewState["SL_Integrate"] = "DESC";
    
            }
            else
            {
                if (ViewState["SL_Integrate"].ToString().Trim() == "ASC")
                {
                    ViewState["SL_Integrate"] = "DESC";
                }
                else
                {
                    ViewState["SL_Integrate"] = "ASC";
                }
            }
            ViewState["Field"] = "SL_Integrate";
            BindData(i);
        }

        protected void ibAdd_Click(object sender, ImageClickEventArgs e)
        {
            if (TextBox_Address.Text == "" || TextBox_Name.Text == "")
            {
                Response.Write("<script language = javascript>alert('请填写完整的信息');</script>");
                return;
            }
            SQLHelper.addNewSchool(TextBox_Name.Text, TextBox_Address.Text);
            Response.Write("<script>alert('我们已录入您的新增信息，会尽快联系该机构，谢谢您的支持！');location.href='" + Request.Url.ToString() + "';</script>");
        }


    }

    /// <summary>
    /// 数据格式，定义好数据的序列化细节
    /// </summary>
    [DataContract]
    public class Person
    {
        [DataMember(Order = 1)]
        public string Name { get; set; }
        [DataMember(Order = 2)]
        public string Address { get; set; }
        [DataMember(Order = 3)]
        public string Tel { get; set; }
    }



    public class OrgItem
    {
        public string Text
        {
            get;
            set;
        }
        public OrgItem(string text)
        {
            Text = text;
        }
    }
    public class OrgItemTag
    {
        public string Tag
        {
            get;
            set;
        }
        public OrgItemTag(string tag)
        {
            Tag = tag;
        }
    }
    /// <summary>
    /// 数据格式，定义好数据的序列化细节
    /// </summary>
    [DataContract]
    public class Location
    {
        [DataMember(Order = 1)]
        public double Longitude { get; set; }
        [DataMember(Order = 2)]
        public double Latitude { get; set; }
        [DataMember(Order = 3)]
        public string Name { get; set; }
        [DataMember(Order = 4)]
        public string Description { get; set; }
    }

}